package com.hyc.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hyc.cloud.service.FlowLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;

/**
 * 这里是类说明.
 *
 * @className: FlowLimitController
 * @author: hyc
 * @date: 2022-02-13 14:14
 */
@RestController
@Slf4j
public class FlowLimitController {

    @Resource
    private FlowLimitService flowLimitService;

    @GetMapping("/testA")
    public String testA() {
        try {
            // 演示阈值类型为线程数的配置
            Thread.sleep(900);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return " **** testA ****";
    }

    @GetMapping("/testB")
    public String testB() {
        log.info("排队等待");
        return " **** testB ****";
    }

    /**
     * 链路流控模式调用测试
     * @title chainModeTest
     * @author hyc
     * @date 2022/2/14 10:48
     * @param
     * @return java.lang.String
     */
    @GetMapping("/chainTest1")
    public String chainTest1() {
        return flowLimitService.chainModeTest();
    }

    /**
     * 链路流控模式调用测试
     * @title chainTest2
     * @author hyc
     * @date 2022/2/14 11:22
     * @param
     * @return java.lang.String
     */
    @GetMapping("/chainTest2")
    public String chainTest2() {
        return flowLimitService.chainModeTest();
    }

    /**
     * 满调用测试熔断降级
     * @title slowTest
     * @author hyc
     * @date 2022/2/14 19:23
     * @param
     * @return java.lang.String
     */
    @GetMapping("/slowTest")
    public String slowTest() {
//        try {
//            // 平均响应时间RT 熔断测试
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        // 测试异常比例 异常数
        Random random = new Random();
        int ran = random.nextInt(2);
        if (ran < 1) {
            int i = 10 / 0;
        }
        log.info("**** slow test ****");
        return "slow test";
    }

    /**
     * sentinel 之 热点key测试方法
     * @title hotKeyTest
     * @author hyc
     * @date 2022年02月14日 22:27
     * @param
     * @return java.lang.String
     */
    @GetMapping("/hotKeyTest")
    @SentinelResource(value = "hotKey", blockHandler = "hotKeyHandler")
    public String hotKeyTest(String par1, String par2) {

        return "success hot key test";
    }

    // 降级限流处理方法 自定义返回限流提示
    public String hotKeyHandler(String par1, String par2, BlockException exception) {

        return "hotKeyHandler method";
    }
}